import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { automaticLogin, Installationdetection } from '@/api/api' // 根据实际路径修改
import { ElMessage } from 'element-plus'
const routes: Array<RouteRecordRaw> = [
	{
		path: '/',
		name: 'index',
		component: () => import('@/views/index.vue'),
		meta: {
			title: '首页',
		},
	},
	{
		path: '/tokenmint',
		name: 'mint',
		component: () => import('@/views/mint.vue'),
		meta: {
			title: '代币铸造',
		},
	},
	{
		path: '/install',
		name: 'Install',
		component: () => import('@/views/install.vue'),
		meta: {
			title: '安装',
		},
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/Login.vue'),
		meta: {
			title: '登陆',
		},
	},
	{
		path: '/admin/',
		name: 'adminindex',
		component: () => import('@/admin/index.vue'),
		meta: {
			title: '后台首页',
		},
	},
	{
		path: '/admin/setting',
		name: 'settings',
		component: () => import('@/admin/setting.vue'),
		meta: {
			title: '网站设置',
		},
	},
	{
		path: '/admin/tokenlogo',
		name: 'tokenlogo',
		component: () => import('@/admin/tokenlogo.vue'),
		meta: {
			title: 'logo上传',
		},
	},
	{
		path: '/admin/Navigation',
		name: 'Navigation',
		component: () => import('@/admin/Navigation.vue'),
		meta: {
			title: '导航设置',
		},
	},
	{
		path: '/admin/div/:page?',
		name: 'div',
		component: () => import('@/admin/divpage.vue'),
		meta: {
			title: '页面DIV',
		},
	},
]

const router = createRouter({
	history: createWebHistory(process.env.BASE_URL),
	routes,
})

// 全局前置守卫

// 全局前置守卫
let previousRoute = null
router.beforeEach(async (to, from, next) => {
	const currentPathArray = to.path.split('/').filter(Boolean)
	const fromPathArray = from.path.split('/').filter(Boolean)

	const requiresLoginPages = ['admin']
	const loginPages = ['login', 'install']

	// 验证登录状态
	if (requiresLoginPages.includes(currentPathArray[0]) || requiresLoginPages.includes(fromPathArray[0])) {
		try {
			const loginResult = await automaticLogin()

			if (loginResult.code === 200) {
				// 登录成功，继续导航
				next()
			} else {
				next('/login')
			}
		} catch (error) {
			next('/')
		}
	} else if (loginPages.includes(currentPathArray[0]) || loginPages.includes(fromPathArray[0])) {
		try {
			const installationStatus = await Installationdetection()

			if (installationStatus) {
				// 已经安装
				if (currentPathArray[0] === 'login') {
					const loginResult = await automaticLogin()
					if (loginResult.code === 200) {
						next('/admin/')
					} else {
						next()
					}
				} else {
					next('/login')
				}
			} else {
				// 没有安装
				if (currentPathArray[0] === 'login') {
					next('/install')
				} else {
					next()
				}
			}
		} catch (error) {
			next('/')
			// next('/install');
		}
	} else {
		// 无需登录验证的页面，直接执行登录函数，不等待结果
		automaticLogin()
		next()
	}
})

export default router
export { previousRoute }
